"""系统提示词管理"""

import os
from pathlib import Path
from typing import Dict, List


class PromptManager:
    """提示词管理器"""
    
    def __init__(self, prompts_dir: str = None):
        if prompts_dir is None:
            prompts_dir = Path(__file__).parent
        self.prompts_dir = Path(prompts_dir)
    
    def _read_file(self, file_path: Path) -> str:
        """读取文件内容"""
        try:
            with open(file_path, "r", encoding="utf-8") as f:
                return f.read().strip()
        except FileNotFoundError:
            return ""
    
    def get_system_prompt(self, deep_research: bool = False) -> str:
        """获取系统提示词"""
        base_prompt = self._read_file(self.prompts_dir / "base_system.txt")
        
        # 核心知识库文件
        knowledge_files = [
            "cairo_basics.md",
            "cairo_advanced_concepts.md", 
            "cairo_code_templates.md",
            "cairo_error_diagnosis.md",
            "defi_and_crosschain.md",
            "starknet_contracts.md"
        ]
        
        # 读取所有知识库内容
        knowledge_content = []
        for file_name in knowledge_files:
            content = self._read_file(self.prompts_dir / "knowledge" / file_name)
            if content:
                knowledge_content.append(f"## {file_name.replace('.md', '').replace('_', ' ').title()}\n{content}")
        
        # 深度研究模式提示
        deep_research_prompt = ""
        if deep_research:
            deep_research_prompt = "\n\n[深度研究模式]\n请进行多阶段分析：\n1. 问题分解\n2. 假设提出\n3. 逐点验证\n4. 汇总结论与不确定点"
        
        # 组合所有提示词
        prompts = [base_prompt] + knowledge_content + [deep_research_prompt]
        return "\n\n".join([p for p in prompts if p])
    
    def get_knowledge_base(self) -> Dict[str, str]:
        """获取知识库内容"""
        knowledge = {}
        knowledge_dir = self.prompts_dir / "knowledge"
        
        if knowledge_dir.exists():
            for file_path in knowledge_dir.glob("*.md"):
                key = file_path.stem
                content = self._read_file(file_path)
                if content:
                    knowledge[key] = content
        
        return knowledge


# 全局提示词管理器实例
prompt_manager = PromptManager()
